package com.drinks.yiniang.ui.fragment.community;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.community.CommunityHotAdapter;
import com.drinks.yiniang.common.help.PayManager;
import com.drinks.yiniang.common.recycler.decoration.CHotStaggeredItemDecoration;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.entity.community.CommunityHotJson;
import com.drinks.yiniang.entity.event.CommunityPublishEvent;
import com.drinks.yiniang.entity.event.PayWXEventBus;
import com.drinks.yiniang.io.api.CommunityApiIO;
import com.drinks.yiniang.ui.activity.camera.CameraActivity;
import com.drinks.yiniang.ui.activity.community.CommunityDetailActivity;
import com.drinks.yiniang.ui.activity.community.CommunityPublishActivity;
import com.drinks.yiniang.ui.activity.community.UserCommunityActivity;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.ActivityUtils;
import com.drinks.yiniang.utils.SharedPreUtils;
import com.hansen.library.ui.widget.refresh.MSwipeRefreshLayout;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.fragment.BaseLazyFragment;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * 社区热门页面
 *
 * @author han
 * A simple {@link Fragment} subclass.
 */
public class CommunityHotFragment extends BaseLazyFragment implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    private MSwipeRefreshLayout refresh_community_hot;
    private BaseRecyclerView rcv_community_hot;
    //添加热门动态
    private ImageView iv_community_hot_add;

    private CommunityHotAdapter mHotAdapter;

    //当前登录用户的id
    private String mCurrentLoginUserId;

    private int mPages;

    public CommunityHotFragment() {
        // Required empty public constructor
    }

    public static CommunityHotFragment newInstance() {
        return new CommunityHotFragment();
    }

    @Override
    protected int getResID() {
        return R.layout.fragment_community_hot;
    }

    @Override
    protected void initView(View mView) {
        refresh_community_hot = mView.findViewById(R.id.refresh_community_hot);

        rcv_community_hot = mView.findViewById(R.id.rcv_community_hot);

        iv_community_hot_add = mView.findViewById(R.id.iv_community_hot_add);
    }

    @Override
    protected void initData() {
        mContext = getActivity();

        mCurrentLoginUserId = SharedPreUtils.getInstance().getUserID();

        initAdater();
    }

    private void initAdater() {
        //2.声名为瀑布流的布局方式: 2列 ,垂直方向
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        //防止条目闪动
        staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);

        rcv_community_hot.setLayoutManager(staggeredGridLayoutManager);
        rcv_community_hot.addItemDecoration(new CHotStaggeredItemDecoration(mContext, 12));

        mHotAdapter = new CommunityHotAdapter(mContext, new ArrayList<CommunityHotJson.CommunityHotList>());
        mHotAdapter.setHeaderAndEmpty(true);
        mHotAdapter.setCenterEmpty(getLayoutInflater(), rcv_community_hot);
        mHotAdapter.bindToRecyclerView(rcv_community_hot);
    }

    @Override
    protected void listener() {
        refresh_community_hot.setOnRefreshListener(this);

        iv_community_hot_add.setOnClickListener(this);

        mHotAdapter.setOnItemClickListener(this);
        mHotAdapter.setOnItemChildClickListener(this);
        mHotAdapter.setOnLoadMoreListener(this, rcv_community_hot);

        if(!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().register(this);
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_community_hot_add://添加
                if(!ActivityUtils.isLogined(this, mContext, true)) {
                    return;
                }
                startActivity(new Intent(mContext, CameraActivity.class));
                break;
            default:
                break;
        }
    }

    @Override
    protected void lazyLoadData() {
        getHotNews();
    }

    @Override
    public void onRefresh() {
        getHotNews();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CommunityPublishEvent event) {
        getHotNews();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        CommunityHotJson.CommunityHotList data = mHotAdapter.getItem(position);

        if(data == null) {
            return;
        }

        Intent intent = new Intent(mContext, CommunityDetailActivity.class);
        intent.putExtra(Constants.KeyCommunityId, data.getId());
        startActivity(intent);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        CommunityHotJson.CommunityHotList data = mHotAdapter.getItem(position);

        if(data == null || StringUtils.isPositiveIntNumber(data.getStores_id())) {
            return;
        }

        Intent mIntent;

        switch (view.getId()) {
            case R.id.iv_community_hot_avatar://用户头像
            case R.id.tv_community_hot_nickname://用户昵称
                if(data.getFans_id() == null || data.getFans_id().equals(mCurrentLoginUserId)) {
                    return;
                }
                mIntent = new Intent(mContext, UserCommunityActivity.class);
                mIntent.putExtra(Constants.KeyUserId, data.getFans_id());
                startActivity(mIntent);
                break;
            case R.id.tv_community_hot_like://点赞、取消点赞
                doLike(data, position);
                break;
            default:
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        CommunityApiIO.getInstance().getHotCommunityNew(mPages, new APIRequestCallback<CommunityHotJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CommunityHotJson res) {
                if (mHotAdapter == null) {
                    return;
                }
                mPages++;
                mHotAdapter.addData(res.getData().getData());

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mHotAdapter.loadMoreComplete();
                } else {
                    mHotAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mHotAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //获取热门动态
    private void getHotNews() {
        if (!refresh_community_hot.isRefreshing()) {
            showLoadingDialog();
        }

        mPages = 1;

        CommunityApiIO.getInstance().getHotCommunityNew(mPages, new APIRequestCallback<CommunityHotJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CommunityHotJson res) {
                if (mHotAdapter == null) {
                    return;
                }
                mPages++;
                mHotAdapter.getData().clear();
                mHotAdapter.addData(res.getData().getData());

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mHotAdapter.loadMoreComplete();
                } else {
                    mHotAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mHotAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                refresh_community_hot.setRefreshing(false);
                dismissDialog();
            }
        });
    }

    private void doLike(final CommunityHotJson.CommunityHotList data, final int pos) {
        if(!ActivityUtils.isLogined(this, mContext, true)) {
            return;
        }

        if (StringUtils.isEmpty(data.getId())) {
            ToastUtils.showShort(R.string.text_community_not_exist);
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityLike(data.getId(), new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                if(CommonUtils.isArrayIndexOutOfBounds(mHotAdapter.getData(), pos)) {
                    return;
                }

                data.setLike_count(res.getData());
                data.setIs_like(Constants.STATUS_GLOBAL_YES.equals(data.getIs_like()) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES);

                mHotAdapter.setData(pos, data);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    @Override
    public void onDestroy() {
        if(EventBus.getDefault().isRegistered(this)) EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
